% select next generation from all seeds matrix
function result = select_next_generation(all_seeds_matrix)

global seeds;
global func;

% sort all_seeds_matrix in decreasing order of fitness

next_seeds_matrix = [];
all_seeds_number = size(all_seeds_matrix, 1);
all_seeds_fitness = zeros(1, all_seeds_number);

for seeds_index = 1: all_seeds_number 
     seed_fitness = func(all_seeds_matrix(seeds_index,:));
     all_seeds_fitness(seeds_index) = seed_fitness;
end

% sort all_seeds_matrix in decreasing order, and let best fitness solution
% be the top one in it.
[~,index] = sort(all_seeds_fitness, 'descend');
all_seeds_matrix = all_seeds_matrix(index,:);
all_seeds_matrix(1,:) = all_seeds_matrix(end,:);

% matlab bug: when adding a column/row into a matrix by manipulating the
% subscription of the matrix will cause error, so change another way.
% ??? Subscripted assignment dimension mismatch
% select best seed
next_seeds_matrix = [next_seeds_matrix; all_seeds_matrix(1,:)];

% maintain the top 2 * seeds locations in all_seeds_matrix
% update all_seeds_matrix and all_seeds_number
if all_seeds_number > 2 * seeds
    all_seeds_matrix = all_seeds_matrix(1 : 2*seeds,:);
    all_seeds_number = size(all_seeds_matrix,1);
end

all_seeds_probability = zeros(1, all_seeds_number);

% calculate all seeds distance between each other
[seeds_distance_total, distance_total] = calculate_seeds_distance(all_seeds_matrix);

% randomly select the n - 1 locations for next according to the probability
% generation
for seed_index = 1 : all_seeds_number
%     selected_seed = all_seeds_matrix(seed_index,:);
%     all_seeds_probability(seed_index) = probability(selected_seed, all_seeds_matrix);
    all_seeds_probability(seed_index) = seeds_distance_total(seed_index) / distance_total;
end
all_seeds_cumulate_probability = cumsum(all_seeds_probability, 2);

for index = 1 :seeds - 1
    hitting_index = 1;
    spinning_wheel = rand;
    while spinning_wheel > all_seeds_cumulate_probability(hitting_index) && ...
                                            hitting_index < all_seeds_number
        hitting_index = hitting_index + 1;
    end
    next_seeds_matrix = [next_seeds_matrix; all_seeds_matrix(hitting_index,:)];
end
result = next_seeds_matrix;
end
